1. Introduction to the CSS Box Model
The CSS Box Model is a fundamental concept that describes how elements are structured and spaced on a webpage. Every element is treated as a rectangular box, which consists of four parts:
- Content: The actual content of the element, such as text or images.
- Padding: The space between the content and the border.
- Border: The border surrounding the padding and content.
- Margin: The space outside the border, separating the element from other elements.
The box model can be visualized as follows:
+---------------------------+
| Margin |
| +---------------------+ |
| | Border | |
| | +---------------+ | |
| | | Padding | | |
| | | +---------+ | | |
| | | | Content | | | |
| | | +---------+ | | |
| | +---------------+ | |
| +---------------------+ |
+---------------------------+
2. Content
The content is the innermost part of the box model. It contains the actual content of the element, such as text, images, or other media.
div {
width: 200px; /* Width of the content */
height: 100px; /* Height of the content */
}
3. Padding
The padding is the space between the content and the border. It adds internal spacing inside the element.
div {
padding: 20px; /* Adds 20px padding on all sides */
padding-top: 10px; /* Adds 10px padding to the top */
padding-right: 15px; /* Adds 15px padding to the right */
padding-bottom: 10px; /* Adds 10px padding to the bottom */
padding-left: 15px; /* Adds 15px padding to the left */
}
4. Border
The border surrounds the padding and content. It can be styled with different widths, colors, and styles.
div {
border: 2px solid #2260e6; /* 2px solid border with blue color */
border-radius: 8px; /* Rounded corners */
}
5. Margin
The margin is the space outside the border. It separates the element from other elements.
div {
margin: 20px; /* Adds 20px margin on all sides */
margin-top: 10px; /* Adds 10px margin to the top */
margin-right: 15px; /* Adds 15px margin to the right */
margin-bottom: 10px; /* Adds 10px margin to the bottom */
margin-left: 15px; /* Adds 15px margin to the left */
}
6. Box-Sizing Property
The box-sizing property controls how the width and height of an element are calculated. The two most common values are:
- content-box (default): Width and height only apply to the content.
- border-box: Width and height include content, padding, and border.
div {
box-sizing: border-box; /* Includes padding and border in width/height */
}